<template>
  <el-drawer v-model="drawerVisible" :z-index="1000" :destroy-on-close="true" size="500px" :title="`${drawerProps.title}`">
    <el-form
      ref="examFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
      :before-close="_colse"
    >
      <el-form-item label="考试名称" prop="testName">
        <el-input v-model="drawerProps.row!.testName" placeholder="请填写考试名称" clearable></el-input>
      </el-form-item>

      <el-form-item label="试卷名称" prop="examId">
        <el-select v-model="drawerProps.row!.examId" placeholder="请选择试卷名称" clearable>
          <el-option v-for="item in examSelList" :key="item.examId" :label="item.examName" :value="item.examId" />
        </el-select>
      </el-form-item>
      <el-form-item label="考场名称" prop="roomName">
        <el-input v-model="drawerProps.row!.roomName" placeholder="请填写考场名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="考场开始时间" prop="startTime">
        <el-date-picker
          style="width: 200px"
          placeholder=""
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          v-model="drawerProps.row!.startTime"
        />
      </el-form-item>
      <el-form-item label="考场结束时间" prop="endTime">
        <el-date-picker
          style="width: 200px"
          placeholder=""
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          v-model="drawerProps.row!.endTime"
        />
      </el-form-item>
      <!-- <div class="handlerBar">
        <div class="handlerBar__header">
          <el-button type="primary" plain :icon="CirclePlus" @click="_addControlItem">新增控制信息</el-button>
        </div>
      </div> -->
      <div class="controlList">
        <div class="controlItem" v-for="item in controlList" :key="item.id">
          <!-- <el-icon class="delBtn" :size="20"><CircleClose @click="_delControlItem(index)" /></el-icon> -->
          <el-select class="deviceId" v-model="item.deviceId" clearable placeholder="请选择装置名称" disabled>
            <el-option v-for="val in deviceSelList" :key="val.deviceId" :label="val.deviceName" :value="val.deviceId" />
          </el-select>
          <el-select v-model="item.teacherId" clearable placeholder="请选择教师">
            <el-option v-for="val in teacherSelList" :key="val.userId" :label="val.userName" :value="val.userId" />
          </el-select>
        </div>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="CabineDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Exam, ResultData } from "@/api/interface";
// import { CirclePlus } from "@element-plus/icons-vue";
import { getExamDtl } from "@/api/modules/exam1Manage/examInfo";
import { getExamSelList } from "@/api/modules/exam1Manage/testPaper";
import { getCabinetSelList } from "@/api/modules/files1Manage/cabinet";
import { getUserSelList } from "@/api/modules/user";
const rules = reactive({
  testName: [{ required: true, trigger: "blur", message: "请填写考试名称" }],
  examId: [{ required: true, trigger: "blur", message: "请选择试卷名称" }],
  roomName: [{ required: true, trigger: "blur", message: "请填写考场名称" }],
  startTime: [{ required: true, trigger: "blur", message: "请选择考试开始时间" }],
  endTime: [{ required: true, trigger: "blur", message: "请选择考试结束时间" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Exam.ResExamInfoList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}
const examSelList: any = ref([]);
const controlList: any = ref([]);
const deviceSelList: any = ref([]);
const teacherSelList: any = ref([]);

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  controlList.value = [];
  if (drawerProps.value.title === "编辑") {
    const { result } = (await getExamDtl({ testId: drawerProps.value.row.testId as number })) as ResultData;
    result.controlList.forEach((item: any, index: number) => {
      controlList.value.push({ id: index + 1, deviceId: item.deviceId, teacherId: item.teacherId });
    });
  }
  getCabinetSelData();
  getUserSelData();
  getExamSelData();
};

// 提交数据（新增/编辑）
const examFormRef = ref<FormInstance>();
/**
 * 新增控制信息
 */
// const _addControlItem = () => {
//   controlList.value.push({ id: controlList.value.length + 1, deviceId: "", teacherId: "" });
// };
/**
 * 删除控制信息
 */
// const _delControlItem = (curIdx: number) => {
//   controlList.value.splice(curIdx, 1);
// };
/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  controlList.value = [];
  examFormRef.value && examFormRef.value.resetFields();
};
/**
 * 获取设备选择列表
 */
const getCabinetSelData = async () => {
  const { result } = (await getCabinetSelList({ pageNum: 1, pageSize: 100000000 })) as ResultData;
  deviceSelList.value = result.dataList;
};
/**
 * 获取用户选择列表
 */
const getUserSelData = async () => {
  const res = await getUserSelList({ userType: "teacher" });
  teacherSelList.value = res.dataList;
};
/**
 * 获取试卷选择列表
 */
const getExamSelData = async () => {
  const res = await getExamSelList();
  examSelList.value = res.dataList;
};
/**
 * 提交信息
 */
const handleSubmit = () => {
  examFormRef.value!.validate(async valid => {
    if (!valid) return;
    let isReturn = false;
    const { testId, testName, examId, roomName, startTime, endTime } = drawerProps.value.row;
    interface params {
      testId?: number;
      testName: string;
      examId: number;
      roomName: number;
      startTime: string;
      endTime: string;
      controlList?: { deviceId: string; teacherId: string }[];
    }
    let params: params = {
      testName: testName as string,
      examId: examId as number,
      roomName: roomName as number,
      startTime: startTime as string,
      endTime: endTime as string,
      controlList: []
    };
    if (drawerProps.value.title === "编辑") params.testId = testId;
    params.controlList = controlList.value.map((item: any) => {
      if (!item.deviceId) {
        isReturn = true;
      } else if (!item.teacherId) {
        isReturn = true;
      }
      try {
        if (isReturn) {
          ElMessage.error("请检查控制信息,控制信息子项不能为空");
          throw Error();
        }
      } catch (err: any) {
        console.log(err.message);
      }
      return {
        deviceId: item.deviceId,
        teacherId: item.teacherId
      };
    });

    if (params.controlList && !params.controlList.length) {
      ElMessage.error("请新增控制信息，控制信息不能为空");
      return false;
    }
    if (isReturn) return false;
    try {
      await drawerProps.value.api!(params);
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
defineExpose({
  acceptParams
});
</script>
<style lang="scss" scope>
.handlerBar {
  width: 100%;
  .handlerBar__header {
    padding: 0 10px;
  }
}
.controlItem {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  margin: 20px 0 0;
  border: 1px solid #eeeeee;
  .deviceId {
    margin-right: 20px;
  }
  .delBtn {
    position: absolute;
    top: -8px;
    right: -8px;
    color: var(--el-color-danger);
    cursor: pointer;
  }
}
</style>
